package com.cropdoctor.service.impl;

import com.cropdoctor.common.CustomException;
import com.cropdoctor.common.Result;
import com.cropdoctor.mapper.SysUserMapper;
import com.cropdoctor.mapper.SysUserRoleRelationMapper;
import com.cropdoctor.model.po.SysUserPo;
import com.cropdoctor.model.po.SysUserRoleRelationPo;
import com.cropdoctor.service.RegisterService;
import com.cropdoctor.util.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    AliOssUtil ossUtil;

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysUserRoleRelationMapper sysUserRoleRelationMapper;

    @Override
    @Transactional
    public Result<String> userRegister(SysUserPo sysUserPo,MultipartFile img) {
        if(img != null){
            String filename = img.getOriginalFilename();
            File tempFile = null;
            byte[] bytes = null;
            try {
                tempFile = File.createTempFile("oss", "temp");
                String absolutePath = tempFile.getAbsolutePath();//临时文件路径
                bytes = img.getBytes();
                img.transferTo(tempFile);
                String url = null;
                //获取原始的文件名
                String originalFilename = tempFile.getName();
                //在oss中存储名字就是UUID + 文件的后缀名
                String objectName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
                url = ossUtil.upload(bytes, "account/"+objectName);
                sysUserPo.setAvatarUrl(url);
            } catch (IOException e) {
                e.printStackTrace();
                throw new CustomException("创建临时文件失败!");
            }finally {
                tempFile.delete();
            }
        }
        //进一步封装sysUserPo
        sysUserPo.setEnabled(1);

        //将数据插入到用户表中
        int result1 = sysUserMapper.insert(sysUserPo);
        //若插入失败，则抛出CustomException异常
        if (result1 <= 0) throw new CustomException("用户表数据插入失败");

        //封装SysUserRoleRelationPo，用户默认权限为user，管理员可以修改权限
        Integer idUser = sysUserPo.getId();
        SysUserRoleRelationPo sysUserRoleRelationPo = new SysUserRoleRelationPo();
        sysUserRoleRelationPo.setUserId(idUser);
        sysUserRoleRelationPo.setRoleId(2);

        //将sysUserRoleRelationPo插入到用户角色关系表中，若插入失败，则抛出CustomException异常
        sysUserRoleRelationMapper.insert(sysUserRoleRelationPo);
        if (result1 <= 0) throw new CustomException("用户角色关系表数据插入失败");

        return Result.success("用户注册成功！");
    }
}
